package com.huterox.second.controller;


import com.huterox.second.dao.message.MainMessage;
import com.huterox.second.dao.pojo.User;
import com.huterox.second.server.UserService;
import com.huterox.second.utils.TokenProccessor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Objects;

@Controller
@ResponseBody
public class Main {
    @Autowired
    MainMessage mainMessage;

    @Autowired
    UserService userService;

    @Autowired
    TokenProccessor tokenProccessor;

    @RequestMapping("/main")
    public MainMessage main(HttpServletRequest request, HttpSession session){
//        能够进来这个页面说明是已经登录了的
        String token = request.getHeader("token");
        Long id = (Long) session.getAttribute("id");
        String name = (String) session.getAttribute("name");
        System.out.println("id:"+id+"-name:"+name+"进入Mian");
        if(id!=null && name!=null){
//            如果有人恶意修改session，我也没辙，反正到时候恶意修改后数据可能是拿不到的
            mainMessage.setSuccess(1);
            mainMessage.setCurrentId(id);
            mainMessage.setCurrentName(name);
        }else {
            User user = userService.selectUserById(
                    Integer.parseInt(Objects.requireNonNull(tokenProccessor.GetIdByToken(token)))
            );
            if (user!=null){
//                我们在这里的目的是为了设置session，这样好进行聊天标记
                session.setAttribute("id",user.getId());
                session.setAttribute("name",user.getUsername());
                mainMessage.setSuccess(1);
                mainMessage.setCurrentId(user.getId());
                mainMessage.setCurrentName(user.getUsername());

            }else {
                mainMessage.setSuccess(0);
            }
        }
        return mainMessage;
    }
}
